package org.example.spring_blog.controller;

import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.apache.catalina.security.SecurityUtil;
import org.example.spring_blog.Constant.Constants;
import org.example.spring_blog.model.Result;
import org.example.spring_blog.model.UserInfo;
import org.example.spring_blog.service.UserService;
import org.example.spring_blog.utils.JWTUtils;
import org.example.spring_blog.utils.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.Map;

@Slf4j
@RequestMapping("/user")
@RestController
public class UserController {

    @Autowired
    private UserService userService;

    @RequestMapping("/login")
    public Result login(String username, String password){
        log.info("UserController#login接收参数: username:{}, password:{}", username, password);
        if(!StringUtils.hasLength(username) || !StringUtils.hasLength(password)){
            return Result.fail("账号和密码不能为空");
        }

        UserInfo userInfo = userService.selectByName(username);
        if(userInfo == null) {
            log.error("用户不存在");
            return Result.fail("用户不存在");
        }
        if (!SecurityUtils.verify(password, userInfo.getPassword())) {
            log.error("密码错误");
            return Result.fail("密码错误");
        }

        //密码正确 返回token
        Map<String,Object> claim = new HashMap<>();
        claim.put(Constants.TOKEN_ID, userInfo.getId());
        claim.put(Constants.TOKEN_USERNAME,userInfo.getUsername());
        String token = JWTUtils.genJwtToken(claim);
        log.info("UserController#login 返回结果token:{}",token);

        return Result.success(token);
    }

    /**
     *
     * 获取当前登录用户的信息
     * @param httpServletRequest
     * @return
     */
    @RequestMapping("/getUserInfo")
    public UserInfo getLoginUserInfo(HttpServletRequest httpServletRequest){
        log.info("获取当前用户信息...");
        //获取token
        String token = httpServletRequest.getHeader(Constants.REQUEST_HEADER_TOKEN);
        //从token中获得ID
        Integer userId = JWTUtils.getIdByToken(token);
        if(userId == null){
            return null;
        }

        UserInfo userInfo = userService.selectById(userId);
        return userInfo;
    }

    /**
     * 获取当前作者信息
     * @param blogId
     * @return
     */
    @RequestMapping("/getAuthorInfo")
    public UserInfo getAuthorInfo(Integer blogId){
        log.info("获取当前作者信息...");
        if(blogId <= 0){
            return null;
        }
        UserInfo userInfo = userService.getAuthorInfo(blogId);

        return userInfo;
    }

}
